import { ref, computed } from 'vue'
import { globalMessage } from '../../../utils/message'
/**
 * 图片上传管理
 */
export interface ImageUploadOptions {
  maxCount?: number
  maxSize?: number // in bytes
  acceptTypes?: string[]
}

export function useImageUpload(options: ImageUploadOptions = {}) {
  const {
    maxCount = 3,
    maxSize = 5 * 1024 * 1024, // 5MB
    acceptTypes = ['image/']
  } = options
  
  const selectedImages = ref<string[]>([])
  const fileInputRef = ref<HTMLInputElement>()
  
  const addImage = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      if (!acceptTypes.some(type => file.type.startsWith(type))) {
        globalMessage.warning('请选择图片文件')
        reject(new Error('Invalid file type'))
        return
      }
      
      if (file.size > maxSize) {
        globalMessage.warning(`图片大小不能超过${maxSize / 1024 / 1024}MB`)
        reject(new Error('File too large'))
        return
      }
      
      if (selectedImages.value.length >= maxCount) {
        globalMessage.warning(`最多只能选择${maxCount}张图片`)
        reject(new Error('Too many images'))
        return
      }
      
      const reader = new FileReader()
      reader.onload = (ev) => {
        const dataUrl = ev.target?.result as string
        selectedImages.value.push(dataUrl)
        resolve(dataUrl)
      }
      reader.onerror = () => {
        reject(new Error('Failed to read file'))
      }
      reader.readAsDataURL(file)
    })
  }
  
  const removeImage = (index: number) => {
    if (index >= 0 && index < selectedImages.value.length) {
      selectedImages.value.splice(index, 1)
    }
  }
  
  const clearImages = () => {
    selectedImages.value = []
  }
  
  const triggerFileInput = () => {
    fileInputRef.value?.click()
  }
  
  const onFileChange = (event: Event) => {
    const files = (event.target as HTMLInputElement).files
    if (!files?.length) return
    
    const file = files[0]
    addImage(file).catch(() => {
      // 错误已在addImage中处理
    })
    
    // 清空input值，允许重复选择同一文件
    ;(event.target as HTMLInputElement).value = ''
  }
  
  const getImagesForUpload = () => {
    return [...selectedImages.value]
  }
  
  const canAddMore = computed(() => selectedImages.value.length < maxCount)
  
  return {
    selectedImages,
    fileInputRef,
    addImage,
    removeImage,
    clearImages,
    triggerFileInput,
    onFileChange,
    getImagesForUpload,
    canAddMore
  }
}